﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Acme.BizTalk.Schemas;
using Microsoft.XLANGs.BaseTypes;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace Acme.BizTalk.Orchestrations.Utilities
{
    /// <summary>
    /// Provides helper methods for the claim loading process orchestration
    /// </summary>
    public class ClaimLoadingProcessHelper
    {
        /// <summary>
        /// Counts the number of claims in a message
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static int CountClaims(XLANGMessage msg)
        {
            XElement claimsBatchElement = XElement.Load(XmlReader.Create((Stream)msg[0].RetrieveAs(typeof(Stream))));
            return CountClaims(claimsBatchElement);
        }
        /// <summary>
        /// Counts the number of claims in a message
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static int CountClaims(XElement claimsBatchElement)
        {            
            string claimElementName = typeof(Acme.BizTalk.Schemas.MessageTypes.Claims.Claim).Name;
            
            var claims = from claim in claimsBatchElement.Elements(XName.Get(claimElementName,  "http://Acme.BizTalk.Schemas.Claims")) select claim;
            return claims.Count();
        }
        /// <summary>
        /// Gets a given claim from a message
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static Acme.BizTalk.Schemas.MessageTypes.Claims.Claim GetClaim(XLANGMessage msg, int index)
        {
            XElement claimsBatchElement = XElement.Load(XmlReader.Create((Stream)msg[0].RetrieveAs(typeof(Stream))));
            return GetClaim(claimsBatchElement, index);
        }
        /// <summary>
        /// Gets a given claim from a message
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static Acme.BizTalk.Schemas.MessageTypes.Claims.Claim GetClaim(XElement claimsBatchElement, int index)
        {
            string claimElementName = typeof(Acme.BizTalk.Schemas.MessageTypes.Claims.Claim).Name;
            XElement claim = claimsBatchElement.Elements(XName.Get(claimElementName, "http://Acme.BizTalk.Schemas.Claims")).ElementAt<XElement>(index);
            XmlSerializer serializer = new XmlSerializer(typeof(Acme.BizTalk.Schemas.MessageTypes.Claims.Claim));
            return (Acme.BizTalk.Schemas.MessageTypes.Claims.Claim)serializer.Deserialize(claim.CreateReader());
        }
    }
}
